const {
  $util,
} = getApp();
let _timer = null;

Page({
  data: {
    currentIndex: 0, // 当前题目index
    currentPageNum: 0, // 当前题号
    totalPageNum: 0, // 题目总数
    rightErrTotalNum: 0, // 已答题数目
    choiceAnswerMap: { // 已答题选择的答案
      choiceAnswerList: [],
    },
    hiddenQueList: true, // 隐藏试卷+列表 true隐藏  false显示
    showList: [], // 试卷列表
    showPaper: false, // false 显示考试说明 true显示试卷
    examChance: true,
    chanceTip: '',
    imgUrl: $util.getImgUrl(),
  },
  btnPrevent: false,
  onLoad(opts) {
    opts.barTitle = opts.barTitle && decodeURIComponent(opts.barTitle) || '考试中心';
    wx.setNavigationBarTitle({
      title: '考试中心',
    });
    this.setData(opts, () => {
      this.loadDetail();
      this.loadInfo();
    });
  },
  loadInfo() {
    $util.request({
      url: 'entry/wxapp/edu.exam.testinfo',
      data: {
        testpaperid: this.data.id,
      },
      success: (res) => {
        this.setData({
          paperInfo: {
            ...res.list,
            total: res.total,
            desc: res.desc,
          },
          time: parseInt(res.timelength) || 0,
        });
      },
    });
  },
  startShowPaper() {
    let that = this;
    let { time } = this.data;

    if ( time && time > 0 ) {
      wx.showModal({
        title: '是否开始考试？',
        content: '考试时间：' + time + '分钟',
        success(result) {
          if (result.confirm === true) {
            that.exam();
          }
        },
      });
    } else {
      that.setData({
        showPaper: true,
      });
      that.exam();
    }
  },
  exam() {
    let that = this;
    $util.request({
      url: 'entry/wxapp/edu.exam.teststart',
      data: {
        testpaperid: this.data.id,
      },
      success: (res) => {
        this.setData({
          recordid: res.record_id,
        });

        if (res.answer_data) {
          // 给被答过的题目加个属性
          let list = res.answer_data;
          const showList = [];
          for (let i = 0; i < list.length; i++) {
            const tempObj = {
              title: list[i].title,
            };
            if (list[i].type === '2') { // 多选题
              list[i].confirmSelectFlag = list[i].options.some(function (v) {
                return v.activeFlag == 1;
              });
              tempObj.state = list[i].confirmSelectFlag || false;
            } else { // 单选题或判断
              list[i].confirmSingleFlag = list[i].options.some(function (v) {
                return v.activeFlag == 1;
              });
              tempObj.state = list[i].confirmSingleFlag || false;
            }
            showList.push(tempObj);
          }

          this.setData({
            currentQue: res.answer_data[0],
            [`choiceAnswerMap.choiceAnswerList`]: res.answer.split(','),
            rightErrTotalNum: res.answer.split(',').length,
            showList,

          });

          wx.setStorageSync('qList', res.answer_data); // 本地缓存存储题目

        }

        if (res.remainingtime === -1) {
          return false;
        }

        if (res.isover === 0) { // 考试时间未完
          res.remainingtime && that.countDownRun(res.remainingtime);
          that.setData({
            showPaper: true,
            maxtime: res.remainingtime,
          });
        } else if (res.isover === 1) { // 考试时间结束
          wx.showModal({
            title: '提示',
            content: '考试时间已经结束,立即交卷',
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                that.submitTestPaper();
              }
            },
          });
        }
      },
    });
  },
  loadDetail() {
    let that = this;
    $util.request({
      url: 'entry/wxapp/edu.exam.newmain',
      data: {
        id: this.data.id,
      },
      success: (res) => {
        const plist = res.result;
        that.setData({
          start_time: res.start_time,
          currentQue: plist[0],
          currentIndex: 0,
          currentPageNum: 1,
          totalPageNum: plist.length,
        });
        wx.setStorageSync('qList', plist); // 本地缓存存储题目
      },
      fail: function (res) {
        if (res.errno === -1) {
          that.setData({
            examChance: false,
            chanceTip: res.message,
          });
        }
      },
    });
  },
  getPrevQuestion() {
    const {
      currentIndex,
      currentPageNum,
    } = this.data;
    const qList = wx.getStorageSync('qList');
    this.setData({
      currentQue: qList[currentIndex - 1],
      currentPageNum: currentPageNum - 1,
      currentIndex: currentIndex - 1,
      confirmFlagNum: 0,
    });
  },
  getNextQuestion() {
    const {
      currentIndex,
      currentPageNum,
    } = this.data;
    const qList = wx.getStorageSync('qList');
    const len = qList.length;
    if (currentPageNum === len) {
      wx.showToast({
        title: '最后一题啦！',
        icon: 'none',
      });
      return;
    }
    this.setData({
      currentQue: qList[currentIndex + 1],
      currentPageNum: currentPageNum + 1,
      currentIndex: currentIndex + 1,
      confirmFlagNum: 0,
    });
  },
  // 单选选择答案
  clickSingleSelection(a) {
    let {
      currentQue,
      choiceAnswerMap,
      currentPageNum,
      currentIndex,
      rightErrTotalNum,
      totalPageNum,
    } = this.data;
    const {
      id,
    } = a.currentTarget.dataset;
    const options = currentQue.options;
    options.forEach((item, index) => {
      if (id === index) {
        item.activeFlag = true; // 选中答案
      } else {
        item.activeFlag = false; // 未选中答案
      }
    });
    !currentQue.confirmSingleFlag && rightErrTotalNum < totalPageNum && (rightErrTotalNum += 1);
    currentQue.confirmSingleFlag = true; // 已答题
    choiceAnswerMap.choiceAnswerList[currentIndex] = `${currentQue.id}:${options[id].answer_type}`;
    const qList = wx.getStorageSync('qList');
    qList[currentPageNum - 1] = currentQue;
    this.setData({
      currentQue,
      rightErrTotalNum,
      choiceAnswerMap,
    });
    wx.setStorageSync('qList', qList);
  },
  // 多选选择
  clickSelection(a) {
    const qList = wx.getStorageSync('qList');
    let {
      currentQue,
      confirmFlagNum,
      currentIndex,
      choiceAnswerMap,
      rightErrTotalNum,
      totalPageNum,
    } = this.data;
    const {
      options,
    } = currentQue;
    const {
      id,
    } = a.currentTarget.dataset;
    const activeFlag = currentQue.options[id].activeFlag;
    if (activeFlag) {
      options[id].activeFlag = 0;
      confirmFlagNum -= 1;
    } else {
      options[id].activeFlag = 1;
      confirmFlagNum += 1;
    }
    const selectAnswer = [];
    options.forEach((op) => {
      op.activeFlag === 1 && (selectAnswer.push(op.answer_type));
    });
    const i = `${currentQue.id}:${selectAnswer.join(';')}`;
    const choiceAnswerList = choiceAnswerMap.choiceAnswerList;
    choiceAnswerList[currentIndex] = i;
    if (selectAnswer.length > 0) {
      !currentQue.confirmSelectFlag && rightErrTotalNum < totalPageNum && (rightErrTotalNum += 1);
      currentQue.confirmSelectFlag = true;
    } else {
      currentQue.confirmSelectFlag && (rightErrTotalNum -= 1);
      currentQue.confirmSelectFlag = false;
    }
    this.setData({
      choiceAnswerMap,
      currentQue,
      confirmFlagNum,
      rightErrTotalNum,
    });
    qList[currentIndex] = currentQue;
    wx.setStorageSync('qList', qList);
  },
  onUnload() {
    clearInterval(_timer);
    // 记录答题
    let that = this;
    let { id, recordid, choiceAnswerMap } = this.data;
    const choice_answers = choiceAnswerMap.choiceAnswerList.join();
    $util.request({
      url: 'entry/wxapp/edu.exam.saveanswer',
      data: {
        id,
        recordid,
        choice_answers,
      },
      success: (res) => {
      },
    });
  },
  clickTestPaper() {
    let list = wx.getStorageSync('qList');
    let m = 0;

    for (let i = 0; i < list.length; i++) {
      if (list[i].confirmSelectFlag && list[i].confirmSelectFlag) {
        m++;
      }
      if (list[i].confirmSingleFlag && list[i].confirmSingleFlag) {
        m++;
      } 
    }

    if (m != list.length) {
      wx.showModal({
        title: '提示',
        content: `还有${list.length - m}题没有作答！`,
        showCancel: false,
      });
      return;
    }
    wx.showModal({
      title: '提示',
      content: '是否结束考试？',
      success: (res) => {
        if (res.confirm) {
          this.submitTestPaper();
        }
      },
    });
  },
  submitTestPaper() {
    const {
      choiceAnswerMap,
      start_time,
      id: e_id,
      barTitle,
      recordid,
    } = this.data;
    const choice_answers = choiceAnswerMap.choiceAnswerList.join();
    if (this.btnPrevent) return;
    this.btnPrevent = true;
    $util.request({
      url: 'entry/wxapp/edu.exam.testfinish',
      data: {
        e_id,
        choice_answers,
        start_time,
        recordid,
      },
      success: (res) => {
        this.btnPrevent = false;
        wx.showModal({
          title: '提示',
          content: `提交成功，本次考试共${res.total}道题，答对${res.suc}道题`,
          showCancel: false,
          success: (result) => {
            if (result.confirm) {
              wx.redirectTo({
                url: `/ws_party_const/pages/education/train/network/test/history-record?paperid=${e_id}&recordid=${res.record_id}&title=${barTitle}`,
              });
            }
          },
        });
      },
    });
  },
  showQueList() {
    // cd
    const qList = wx.getStorageSync('qList');
    let {
      hiddenQueList,
    } = this.data;

    hiddenQueList = !hiddenQueList;

    let list = wx.getStorageSync('qList');
    const showList = [];
    for (let i = 0; i < list.length; i++) {
      const tempObj = {
        title: list[i].title,
      };
      if (list[i].type === '2') { // 多选题
        list[i].confirmSelectFlag = list[i].options.some(function (v) {
          return v.activeFlag == 1;
        });
        tempObj.state = list[i].confirmSelectFlag || false;
      } else { // 单选题或判断
        list[i].confirmSingleFlag = list[i].options.some(function (v) {
          return v.activeFlag == 1;
        });
        tempObj.state = list[i].confirmSingleFlag || false;
      }
      showList.push(tempObj);
    }

    this.setData({
      showList,
      hiddenQueList,
    });

  },
  showQuestion(e) {
    const { index } = e.currentTarget.dataset;
    const qList = wx.getStorageSync('qList');
    this.setData({
      currentQue: qList[index],
      currentIndex: index,
      currentPageNum: index + 1,
      hiddenQueList: true,
    });
  },
  countDownRun(leftTime) {
    clearInterval(_timer);
    let that = this;
    let timeout = leftTime || 0;
    _timer = setTimeout(() => {
      leftTime--;
      that.countDownRun(leftTime);
    }, 1000);
    // if (leftTime === 30 * 1000) {
    //   wx.showToast({
    //     title: '还剩30秒',
    //     icon: 'none',
    //   });
    // }
    that.saveTime(leftTime);
  },

  saveTime(leftTime) {
    let that = this;
    let hours = parseInt(leftTime/3600%60, 10);
    let minutes = parseInt(leftTime/60%60, 10);
    let seconds = parseInt(leftTime%60, 10);
    let countDownMsg = seconds < 10 ? (hours * 60 + minutes) + '分0' + seconds + '秒' : (hours * 60 + minutes) + '分' + seconds + '秒';
    if (leftTime <= 0) {
      clearInterval(_timer);
      wx.showModal({
        title: '提示',
        content: '考试时间已经结束,立即交卷',
        showCancel: false,
        success(res) {
          that.submitTestPaper(); // 时间到自动交卷
        },
      });
    }
    this.setData({
      maxtime: leftTime,
      countDownMsg,
    });
  },
});
